<template>
	<view class="container" :class="themeClass">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="nav-bar">
				<view class="nav-back" @tap="goBack">
					<uni-icons type="left" size="20" color="#333"></uni-icons>
					<text class="back-text">返回</text>
				</view>
				<text class="nav-title">关闭两步验证</text>
				<view class="nav-right"></view>
			</view>
		</view>

		<!-- 页面内容 -->
		<view class="content">
			<!-- 警告信息 -->
			<view class="warning-section">
				<view class="warning-icon">
					<uni-icons type="info" size="40" color="#fa541c"></uni-icons>
				</view>
				<text class="warning-title">安全警告</text>
				<text class="warning-desc">关闭两步验证将降低您的账号安全性，建议您仅在必要时关闭此功能</text>
			</view>

			<!-- 验证表单 -->
			<view class="form-section">
				<text class="form-title">身份验证</text>
				<text class="form-desc">请选择一种方式验证您的身份</text>

				<!-- 验证方式选择 -->
				<view class="verify-methods">
					<view 
						class="method-item" 
						:class="{ active: selectedMethod === 'authenticator' }"
						@tap="selectMethod('authenticator')"
					>
						<view class="method-radio">
							<view v-if="selectedMethod === 'authenticator'" class="radio-dot"></view>
						</view>
						<view class="method-info">
							<text class="method-title">身份验证器</text>
							<text class="method-desc">使用身份验证器应用中的6位验证码</text>
						</view>
						<uni-icons type="right" size="16" color="#ccc"></uni-icons>
					</view>

					<view 
						class="method-item" 
						:class="{ active: selectedMethod === 'backup' }"
						@tap="selectMethod('backup')"
					>
						<view class="method-radio">
							<view v-if="selectedMethod === 'backup'" class="radio-dot"></view>
						</view>
						<view class="method-info">
							<text class="method-title">备用恢复代码</text>
							<text class="method-desc">使用设置两步验证时保存的备用代码</text>
						</view>
						<uni-icons type="right" size="16" color="#ccc"></uni-icons>
					</view>
				</view>

				<!-- 验证码输入 - 身份验证器 -->
				<view v-if="selectedMethod === 'authenticator'" class="input-section">
					<text class="input-label">验证码</text>
					<view class="code-input-group">
						<input 
							v-for="(digit, index) in codeDigits" 
							:key="index"
							class="code-digit" 
							type="number" 
							maxlength="1"
							v-model="codeDigits[index]"
							@input="onCodeInput(index, $event)"
							@focus="onCodeFocus(index)"
						/>
					</view>
					<text class="input-tips">请输入身份验证器应用中显示的6位验证码</text>
					
					<!-- 开发阶段：手动获取验证码按钮 -->
					<view class="dev-tools">
						<uni-button 
							class="get-code-btn" 
							size="mini" 
							type="default"
							@tap="autoFillCode"
						>
							获取验证码
						</uni-button>
					</view>
				</view>

				<!-- 备用代码输入 -->
				<view v-if="selectedMethod === 'backup'" class="input-section">
					<text class="input-label">备用恢复代码</text>
					<view class="backup-input-wrapper">
						<input 
							class="backup-input" 
							type="text" 
							placeholder="请输入备用恢复代码"
							v-model="backupCode"
							@input="onBackupCodeInput"
						/>
					</view>
					<text class="input-tips">请输入设置两步验证时保存的8位备用恢复代码</text>
					
					<!-- 开发阶段：手动获取备用代码按钮 -->
					<view class="dev-tools">
						<uni-button 
							class="get-backup-btn" 
							size="mini" 
							type="default"
							@tap="autoFillBackupCode"
						>
							获取备用代码
						</uni-button>
					</view>
				</view>

				<!-- 确认关闭 -->
				<view class="confirm-section">
					<view class="confirm-checkbox" @tap="toggleConfirm">
						<view class="checkbox" :class="{ checked: isConfirmed }">
							<uni-icons v-if="isConfirmed" type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
						</view>
						<text class="checkbox-text">我确认要关闭两步验证，并了解这会降低账号安全性</text>
					</view>
				</view>

				<!-- 关闭按钮 -->
				<uni-button 
					class="disable-btn" 
					type="warn"
					:disabled="!canDisable"
					:loading="isDisabling"
					@tap="disable2FA"
				>
					{{ isDisabling ? '关闭中...' : '确认关闭两步验证' }}
				</uni-button>

				<!-- 取消按钮 -->
				<uni-button class="cancel-btn" @tap="goBack">取消</uni-button>
			</view>

			<!-- 帮助信息 -->
			<view class="help-section">
				<view class="help-title">
					<uni-icons type="help" size="16" color="#1890ff"></uni-icons>
					<text class="help-text">需要帮助？</text>
				</view>
				<view class="help-list">
					<text class="help-item">• 如果您丢失了身份验证器设备，请使用备用恢复代码</text>
					<text class="help-item">• 如果您没有备用代码，请联系客服进行人工验证</text>
					<text class="help-item">• 关闭两步验证后，建议立即更改密码</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
	import themeManager from '@/utils/theme.js';

	// 响应式数据
	const selectedMethod = ref('authenticator');
	const codeDigits = ref(['', '', '', '', '', '']);
	const backupCode = ref('');
	const isConfirmed = ref(false);
	const isDisabling = ref(false);
	const themeClass = ref(themeManager.getThemeClass());

	// 计算属性
	const canDisable = computed(() => {
		if (!isConfirmed.value) return false;
		
		if (selectedMethod.value === 'authenticator') {
			return codeDigits.value.every(digit => digit !== '');
		} else if (selectedMethod.value === 'backup') {
			return backupCode.value.length === 8;
		}
		
		return false;
	});

	const verificationCode = computed(() => {
		if (selectedMethod.value === 'authenticator') {
			return codeDigits.value.join('');
		} else {
			return backupCode.value;
		}
	});

	// 主题变化监听
	const handleThemeChange = (isNightMode: boolean) => {
		themeClass.value = themeManager.getThemeClass();
	};

	// 选择验证方式
	const selectMethod = (method: string) => {
		selectedMethod.value = method;
		// 清空输入
		codeDigits.value = ['', '', '', '', '', ''];
		backupCode.value = '';
	};

	// 确认勾选切换
	const toggleConfirm = () => {
		isConfirmed.value = !isConfirmed.value;
	};

	// 验证码输入处理
	const onCodeInput = (index: number, event: any) => {
		const value = event.detail.value;
		if (value && /^\d$/.test(value)) {
			codeDigits.value[index] = value;
			// 自动跳转到下一个输入框
			if (index < 5) {
				nextTick(() => {
					const nextInput = document.querySelector(`.code-digit:nth-child(${index + 2})`);
					if (nextInput) {
						(nextInput as HTMLInputElement).focus();
					}
				});
			}
		} else {
			codeDigits.value[index] = '';
		}
	};

	const onCodeFocus = (index: number) => {
		codeDigits.value[index] = '';
	};

	// 生成6位随机验证码
	const generateRandomCode = () => {
		return Math.floor(100000 + Math.random() * 900000).toString();
	};

	// 生成8位随机备用代码
	const generateBackupCode = () => {
		return Math.random().toString(36).substring(2, 10).toUpperCase();
	};

	// 自动填入验证码（开发阶段）
	const autoFillCode = () => {
		const verifyCode = generateRandomCode();
		
		// 显示验证码提示
		uni.showToast({
			title: `验证码: ${verifyCode}`,
			icon: 'none',
			duration: 5000
		});
		
		// 自动填入验证码
		setTimeout(() => {
			codeDigits.value = verifyCode.split('');
			console.log(`两步验证码: ${verifyCode}`);
		}, 1000);
	};

	// 自动填入备用代码（开发阶段）
	const autoFillBackupCode = () => {
		const backupCodeValue = generateBackupCode();
		
		// 显示备用代码提示
		uni.showToast({
			title: `备用代码: ${backupCodeValue}`,
			icon: 'none',
			duration: 5000
		});
		
		// 自动填入备用代码
		setTimeout(() => {
			backupCode.value = backupCodeValue;
			console.log(`备用恢复代码: ${backupCodeValue}`);
		}, 1000);
	};

	// 备用代码输入处理
	const onBackupCodeInput = (event: any) => {
		backupCode.value = event.detail.value.replace(/\D/g, '').slice(0, 8);
	};

	// ==================== 后端接口定义 ====================
	// 前端人员：关闭两步验证
	// BACKEND REQUIRED - 后端开发人员请实现以下接口
	// 
	// POST /api/account/security/2fa/disable
	// 请求头: Authorization: Bearer {token}
	// 请求体: {
	//   "method": "authenticator",      // 验证方式：authenticator 或 backup
	//   "code": "123456"               // 验证码或备用代码
	// }
	// 响应 200: { "success": true, "message": "两步验证已关闭" }
	// 响应 400: { "success": false, "message": "验证码错误" }
	// 响应 404: { "success": false, "message": "两步验证未开启" }
	// 响应 410: { "success": false, "message": "验证码已过期" }
	// 响应 422: { "success": false, "message": "备用代码已使用" }
	// 响应 500: { "success": false, "message": "关闭失败" }
	const disable2FA = () => {
		if (!canDisable.value || isDisabling.value) return;

		// 二次确认
		uni.showModal({
			title: '最后确认',
			content: '确定要关闭两步验证吗？这将降低您的账号安全性。',
			confirmText: '确认关闭',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					performDisable2FA();
				}
			}
		});
	};

	const performDisable2FA = () => {
		isDisabling.value = true;

		// 显示加载提示
		uni.showLoading({
			title: '关闭中...'
		});

		// 模拟网络延迟
		setTimeout(() => {
			uni.hideLoading();
			
			// 直接处理关闭两步验证（开发阶段）
			uni.showToast({ title: '两步验证已关闭', icon: 'success' });
			
			// 通知父页面更新安全信息
			uni.$emit('securityInfoUpdated', {
				type: 'twoFactor',
				value: false
			});
			
			// 显示安全提醒
			setTimeout(() => {
				uni.showModal({
					title: '安全提醒',
					content: '两步验证已关闭，建议您立即更改密码以保护账号安全。',
					confirmText: '去更改密码',
					cancelText: '稍后处理',
					success: (modalRes) => {
						if (modalRes.confirm) {
							uni.navigateTo({ url: '/pages/password/password' });
						} else {
							uni.navigateBack();
						}
					}
				});
			}, 1500);
			
			isDisabling.value = false;
		}, 1000);
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 生命周期
	onMounted(() => {
		themeManager.addListener(handleThemeChange);
	});

	onUnmounted(() => {
		themeManager.removeListener(handleThemeChange);
	});
</script>

<style>
	page {
		background-color: #f5f6fa;
	}

	.container {
		min-height: 100vh;
		background-color: #f5f6fa;
	}

	/* 顶部导航栏 */
	.header {
		background: #ffffff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		height: 88rpx;
	}

	.nav-title {
		font-size: 18px;
		font-weight: 600;
		color: #333;
	}

	.nav-back {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 10rpx 16rpx;
		border-radius: 8rpx;
		transition: background-color 0.2s ease;
		cursor: pointer;
	}

	.nav-back:active {
		background-color: rgba(0, 0, 0, 0.05);
	}

	.back-text {
		font-size: 16px;
		color: #333;
		font-weight: 500;
	}

	.nav-right {
		width: 40rpx;
	}

	/* 页面内容 */
	.content {
		padding: 40rpx 30rpx;
	}

	/* 警告信息 */
	.warning-section {
		text-align: center;
		margin-bottom: 40rpx;
		background: #fff2e8;
		border: 2rpx solid #ffbb96;
		border-radius: 16rpx;
		padding: 40rpx;
	}

	.warning-icon {
		width: 100rpx;
		height: 100rpx;
		background: linear-gradient(135deg, #fa541c, #ff7a45);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 24rpx;
		box-shadow: 0 8rpx 32rpx rgba(250, 84, 28, 0.3);
	}

	.warning-title {
		display: block;
		font-size: 20px;
		font-weight: 700;
		color: #fa541c;
		margin-bottom: 16rpx;
	}

	.warning-desc {
		display: block;
		font-size: 14px;
		color: #d4380d;
		line-height: 1.6;
	}

	/* 表单区域 */
	.form-section {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		margin-bottom: 30rpx;
	}

	.form-title {
		display: block;
		font-size: 20px;
		font-weight: 700;
		color: #333;
		margin-bottom: 12rpx;
	}

	.form-desc {
		display: block;
		font-size: 14px;
		color: #666;
		margin-bottom: 30rpx;
		line-height: 1.6;
	}

	/* 验证方式选择 */
	.verify-methods {
		margin-bottom: 40rpx;
	}

	.method-item {
		display: flex;
		align-items: center;
		gap: 16rpx;
		padding: 24rpx;
		background: #f8f9fa;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.method-item:last-child {
		margin-bottom: 0;
	}

	.method-item.active {
		background: #e6f7ff;
		border-color: #1890ff;
	}

	.method-item:active {
		transform: scale(0.98);
	}

	.method-radio {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #d9d9d9;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}

	.method-item.active .method-radio {
		border-color: #1890ff;
		background: #1890ff;
	}

	.radio-dot {
		width: 16rpx;
		height: 16rpx;
		background: #ffffff;
		border-radius: 50%;
	}

	.method-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 6rpx;
	}

	.method-title {
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}

	.method-desc {
		font-size: 12px;
		color: #999;
		line-height: 1.4;
	}

	/* 输入区域 */
	.input-section {
		margin-bottom: 40rpx;
	}

	.input-label {
		display: block;
		font-size: 16px;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	.code-input-group {
		display: flex;
		justify-content: center;
		gap: 16rpx;
		margin-bottom: 16rpx;
	}

	.code-digit {
		width: 80rpx;
		height: 80rpx;
		background: #f8f9fa;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		text-align: center;
		font-size: 24px;
		font-weight: 600;
		color: #333;
		transition: all 0.3s ease;
	}

	.code-digit:focus {
		border-color: #1890ff;
		background: #ffffff;
		box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
	}

	.backup-input-wrapper {
		margin-bottom: 16rpx;
	}

	.backup-input {
		width: 100%;
		height: 88rpx;
		background: #f8f9fa;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 16px;
		color: #333;
		text-align: center;
		letter-spacing: 4rpx;
		box-sizing: border-box;
		transition: all 0.3s ease;
	}

	.backup-input:focus {
		border-color: #1890ff;
		background: #ffffff;
		box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
	}

	.input-tips {
		display: block;
		font-size: 12px;
		color: #999;
		text-align: center;
		line-height: 1.4;
	}

	/* 确认区域 */
	.confirm-section {
		margin-bottom: 40rpx;
	}

	.confirm-checkbox {
		display: flex;
		align-items: flex-start;
		gap: 12rpx;
		cursor: pointer;
	}

	.checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #d9d9d9;
		border-radius: 6rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		transition: all 0.3s ease;
	}

	.checkbox.checked {
		background: #ff4d4f;
		border-color: #ff4d4f;
	}

	.checkbox-text {
		font-size: 14px;
		color: #666;
		line-height: 1.6;
		flex: 1;
	}

	/* 按钮 */
	.disable-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #ff4d4f, #ff7875);
		color: #ffffff;
		border-radius: 12rpx;
		font-size: 18px;
		font-weight: 600;
		border: none;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(255, 77, 79, 0.3);
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	.disable-btn:disabled {
		background: #d9d9d9;
		color: #999;
		box-shadow: none;
	}

	.disable-btn:active:not(:disabled) {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.3);
	}

	.cancel-btn {
		width: 100%;
		height: 88rpx;
		background: #f8f9fa;
		color: #666;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		font-size: 16px;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	/* 帮助信息 */
	.help-section {
		background: #f8f9ff;
		border: 2rpx solid #e6f7ff;
		border-radius: 16rpx;
		padding: 30rpx;
	}

	.help-title {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-bottom: 20rpx;
	}

	.help-text {
		font-size: 16px;
		font-weight: 600;
		color: #1890ff;
	}

	.help-list {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.help-item {
		font-size: 14px;
		color: #666;
		line-height: 1.6;
	}

	/* 开发工具样式 */
	.dev-tools {
		margin-top: 32rpx;
		display: flex;
		justify-content: center;
	}

	.get-code-btn, .get-backup-btn {
		height: 64rpx;
		padding: 0 32rpx;
		background: linear-gradient(135deg, #fa8c16, #ffa940);
		color: #ffffff;
		border-radius: 8rpx;
		font-size: 14px;
		font-weight: 500;
		border: none;
		box-shadow: 0 2rpx 8rpx rgba(250, 140, 22, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	/* 夜间模式适配 */
	.night-mode {
		background-color: #1a1a1a;
	}

	.night-mode .header {
		background: #2c2c2c;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
	}

	.night-mode .nav-title {
		color: #e0e0e0;
	}

	.night-mode .nav-back:active {
		background-color: rgba(255, 255, 255, 0.1);
	}

	.night-mode .back-text {
		color: #e0e0e0;
	}

	.night-mode .warning-section {
		background: #2a1f1a;
		border-color: #3a2a1a;
	}

	.night-mode .warning-title {
		color: #ff7875;
	}

	.night-mode .warning-desc {
		color: #ff9c99;
	}

	.night-mode .form-section {
		background: #2c2c2c;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
	}

	.night-mode .form-title {
		color: #e0e0e0;
	}

	.night-mode .form-desc {
		color: #b0b0b0;
	}

	.night-mode .method-item {
		background: #3a3a3a;
		border-color: #4a4a4a;
	}

	.night-mode .method-item.active {
		background: #1a2a3a;
		border-color: #1890ff;
	}

	.night-mode .method-title {
		color: #e0e0e0;
	}

	.night-mode .method-desc {
		color: #b0b0b0;
	}

	.night-mode .input-label {
		color: #e0e0e0;
	}

	.night-mode .code-digit {
		background: #3a3a3a;
		border-color: #4a4a4a;
		color: #e0e0e0;
	}

	.night-mode .code-digit:focus {
		background: #3a3a3a;
	}

	.night-mode .backup-input {
		background: #3a3a3a;
		border-color: #4a4a4a;
		color: #e0e0e0;
	}

	.night-mode .backup-input:focus {
		background: #3a3a3a;
	}

	.night-mode .checkbox {
		border-color: #4a4a4a;
	}

	.night-mode .checkbox-text {
		color: #b0b0b0;
	}

	.night-mode .cancel-btn {
		background: #3a3a3a;
		color: #e0e0e0;
		border-color: #4a4a4a;
	}

	.night-mode .help-section {
		background: #1a1a2a;
		border-color: #2a2a3a;
	}

	.night-mode .help-item {
		color: #b0b0b0;
	}
</style>


